<?
/**
 * Class to manage database connections
 * Singleton
 */
class MySQL{

	/**
	 * Database connection
	 *
	 * @var Object
	 */
	private $db_con;
	
	/**
	 * Server.
	 *
	 * @var string
	 */
	private $db_host;
	
	/**
	 * Port.
	 *
	 * @var string
	 */
	private $db_port;
	
	/**
	 * DB name
	 *
	 * @var string
	 */
	private $db_name;
	
	/**
	 * DB user
	 *
	 * @var string
	 */
	private $db_user;
	
	/**
	 * BD pass
	 *
	 * @var string
	 */
	private $db_pass;

	/**
	 * Instance - Singleton Pattern
	 * 
	 * @var MySQL
	 */
	private static $instance;

	/**
	 * Construct
	 * Stablish the attributes needed to connect and make the connection
	 * Obtains the connection parameters from constants which follow this format:
	 * 
	 *	MYSQL_name_VARIABLE (i.e. MYSQL_LOCAL_SERVER)
	 * 
	 * We must have defined: SERVER, PORT, DDBB, USER and PASS
	 *
	 * @param string $name Name of the connection.
	 */
	private function __construct(){
		
		$this->db_host = MYSQL_SERVER;
		$this->db_port = MYSQL_PORT;
		$this->db_name = MYSQL_DDBB;
		$this->db_user = MYSQL_USER;
		$this->db_pass = MYSQL_PASS;
		
	}

	/**
	 * Stablishing connection
	 */
	private function connect(){
		$this->db_con = @mysql_connect($this->db_host.":".$this->db_port, $this->db_user, $this->db_pass);

		if(!$this->db_con)
			throw new Exception("Can't connect to the database");

		if(!@mysql_select_db($this->db_name, $this->db_con))
			throw new Exception("There is a problem with the database connection.");
			
		//mysql_query("SET NAMES 'utf8'");
	}

	/**
	 * Query the database and return the result, NULL in error case
	 *
	 * @param string $query 
	 * @return Object $result Resource returned from mysql_query. NULL in error case
	 */
	public function query($query){
		$this->connect();
		$result = mysql_query($query, $this->db_con);
		//$this->close();
		if($result)
			return $result;
		else
			return null;
	}
	
	/**
	 * Get the last insert id after a INSERT INTO query in a table with an autoincrement primary key
	 * 
	 * @return integer $id 
	 */
	public function last_insert_id(){
		  return @mysql_insert_id($this->db_con);
	}

	/**
	 * Close the connection
	 */
	public function close(){
		if($this->db_con)
			@mysql_close($this->db_con);
	}

	/**
	 * The singleton method
	 * @return MySQL
	 */
    public static function get_instance(){
        if (!isset(self::$instance)) {
            self::$instance = new MySQL();
        }

		self::$instance->connect();
        return self::$instance;
    }

	// Prevent users to clone the instance
    public function __clone(){
        trigger_error('Clone is not allowed.', E_USER_ERROR);
    }
}
?>